﻿using B.Z.BasicData.Domain.Entity.Authorize;
using B.Z.BasicData.ErrorCode;
using B.Z.BasicData.Infrastructure;
using MediatR;

namespace B.Z.BasicData.API.Write.Application.Role
{
    public class UserRoleAddCommandHandler : IRequestHandler<UserRoleAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<T_UserRole> urRepository;

        public UserRoleAddCommandHandler(IBaseRepository<T_UserRole> urRepository)
        {
            this.urRepository = urRepository;
        }

        public async Task<APIResult<int>> Handle(UserRoleAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            result.Code = APIEnum.ok;
            result.Message = "分配成功";
            
            List<int> userArr = request.UidList.Split(',').Select(p => Convert.ToInt32(p)).ToList();

            if (userArr.Count > 0)
            {
                foreach (var item in userArr)
                {
                    var list = urRepository.GetAll().Where(x => x.Rid == request.Rid&&x.Uid==item).ToList();
                    urRepository.Del(list);
                }
               
            }
            foreach (var item in userArr)
            {
                T_UserRole urs = new()
                {
                    Uid = item,
                    Rid = request.Rid,
                    CreateTime = DateTime.Now,
                };
                result.Data += await urRepository.Add(urs);
            }
            return await Task.FromResult(result);
        }
    }
}
